﻿using FellowOakDicom.Network.Client;
using FellowOakDicom.Network;
using FellowOakDicom;
using SuporeSliplampApp.Control;
using SuporeSliplampApp.Models;
using SuporeSliplampApp.Service;
using SuporeSliplampApp.Util;
using SuporeSliplampApp.ViewModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Supore.APP.UI.Controls.Notify;
using iTextSharp.text;
using ControlzEx.Standard;

namespace SuporeSliplampApp.Views
{
    /// <summary>
    /// OpenPatients.xaml 的交互逻辑
    /// </summary>
    public partial class OpenPatients : Window
    {

        AddPatientService service = new AddPatientService();
        EditPatientService service2 = new EditPatientService();

        List<PatientModel> patientList = new List<PatientModel>();
        AddPatientService patientService = new AddPatientService();
        ObservableCollection<PatientModel> bindList;
        OpenPatientsModel openPatientsModel = new OpenPatientsModel();
        List<PatientModel> patientList2 = new List<PatientModel>();

        public OpenPatients()
        {
            InitializeComponent();

            //this.grid.ItemsSource = patientList2;

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private List<PatientModel> getPatient()
        {
            return patientService.GetAllPatients();
        }

        private void initData()
        {
            patientList = getPatient();
            //this.grid.Items.Clear();
            //this.grid.ItemsSource = patientList;

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {

            var model = this.grid.SelectedItem as PatientModel;
            MainViewModel.GetInstance().patientModel.Name = model.Name;
            MainViewModel.GetInstance().patientModel.P_ID = model.P_ID;
            MainViewModel.GetInstance().patientModel.SEX = model.SEX;
            MainViewModel.GetInstance().patientModel.Str_Birth = model.Birth.ToShortDateString();
            MainViewModel.GetInstance().patientModel.Birth = model.Birth;
            MainViewModel.GetInstance().patientModel.Adreess = model.Adreess;
            MainViewModel.GetInstance().patientModel.PhoneNum = model.PhoneNum;
            MainViewModel.GetInstance().patientModel.Email = model.Email;
            MainViewModel.GetInstance().patientModel.Creator = model.Creator;
            util.isPatientSelected = true;

            if (service.PicExist(model.P_ID))
            {
                HomeViewModel.GetInstance().NavPage("SuporeSliplampApp.Views.CameraView");
            }
            else if(!service.PicExist(model.P_ID))
            {
                HomeViewModel.GetInstance().NavPage("SuporeSliplampApp.Views.MainView");
            }

            this.Close();
        }


        private void Confirm_Click(object sender, RoutedEventArgs e)
        {
            if (Common.isAddToNow)
            {
                var model = this.grid.SelectedItem as PatientModel;
                MainViewModel.GetInstance().patientModel.Name = model.Name;
                MainViewModel.GetInstance().patientModel.P_ID = model.P_ID;
                MainViewModel.GetInstance().patientModel.SEX = model.SEX;
                MainViewModel.GetInstance().patientModel.Str_Birth = model.Birth.ToShortDateString();
                MainViewModel.GetInstance().patientModel.Birth = model.Birth;
                MainViewModel.GetInstance().patientModel.Adreess = model.Adreess;
                MainViewModel.GetInstance().patientModel.PhoneNum = model.PhoneNum;
                MainViewModel.GetInstance().patientModel.Email = model.Email;
                MainViewModel.GetInstance().patientModel.Creator = model.Creator;
                util.isPatientSelected = true;

                ResultModel result = new ResultModel();
                ScrollControl sc = new ScrollControl();
                ListControlModel photo = new ListControlModel();
                VideoModel video = new VideoModel();
                if (Common.scrolllist.Count > 0)
                {
                    for (int i = 0; i < Common.scrolllist.Count; i++)
                    {
                        sc = (ScrollControl)Common.scrolllist[i];
                        photo = sc.DataContext as ListControlModel;
                        video = sc.DataContext as VideoModel;
                        try
                        {
                            if (video == null)
                            {
                                result.Id = model.P_ID;
                                result.Description = null;
                                result.Date = DateTime.Now;
                                result.Name = photo.ImageName;
                                result.Path = photo.ImgPath;
                                service.SaveResults(result);
                            }
                            else
                            {
                                result.Id = model.P_ID;
                                result.Description = null;
                                result.Date = DateTime.Now;
                                result.Path = video.VideoPath;
                                result.Name = video.Name;
                                service.SaveResults(result);
                            }
                        }
                        catch { }
                    }
                }

                HomeViewModel.GetInstance().NavPage("SuporeSliplampApp.Views.CameraView");
                this.Close();
            }
            else
            {
                var model = this.grid.SelectedItem as PatientModel;
                if (model != null)
                {
                    MainViewModel.GetInstance().patientModel.Name = model.Name;
                    MainViewModel.GetInstance().patientModel.P_ID = model.P_ID;
                    MainViewModel.GetInstance().patientModel.SEX = model.SEX;
                    MainViewModel.GetInstance().patientModel.Str_Birth = model.Birth.ToShortDateString();
                    MainViewModel.GetInstance().patientModel.Birth = model.Birth;
                    MainViewModel.GetInstance().patientModel.Adreess = model.Adreess;
                    MainViewModel.GetInstance().patientModel.PhoneNum = model.PhoneNum;
                    MainViewModel.GetInstance().patientModel.Email = model.Email;
                    MainViewModel.GetInstance().patientModel.Creator = model.Creator;
                    util.isPatientSelected = true;

                    if (service.PicExist(model.P_ID))
                    {
                        HomeViewModel.GetInstance().NavPage("SuporeSliplampApp.Views.CameraView");
                    }
                    else if (!service.PicExist(model.P_ID))
                    {
                        HomeViewModel.GetInstance().NavPage("SuporeSliplampApp.Views.MainView");
                    }

                    this.Close();

                }
                else if (model == null)
                {
                    return;
                }
            }
        }


        private void Button_Click_2(object sender, RoutedEventArgs e)
        {

            var model = this.grid.SelectedItem as PatientModel;
            if(model != null)
            { 
                MainViewModel.GetInstance().patientModel.Name = model.Name;
                MainViewModel.GetInstance().patientModel.P_ID = model.P_ID;
                MainViewModel.GetInstance().patientModel.SEX = model.SEX;
                MainViewModel.GetInstance().patientModel.Str_Birth = model.Birth.ToShortDateString();
                MainViewModel.GetInstance().patientModel.Birth = model.Birth;
                MainViewModel.GetInstance().patientModel.Adreess = model.Adreess;
                MainViewModel.GetInstance().patientModel.PhoneNum = model.PhoneNum;
                MainViewModel.GetInstance().patientModel.Email = model.Email;
                MainViewModel.GetInstance().patientModel.Creator = model.Creator;
                util.isPatientSelected = true;

                if (service.PicExist(model.P_ID))
                {
                    HomeViewModel.GetInstance().NavPage("SuporeSliplampApp.Views.CameraView");
                }
                else if (!service.PicExist(model.P_ID))
                {
                    HomeViewModel.GetInstance().NavPage("SuporeSliplampApp.Views.MainView");
                }

                this.Close();
            }

        }


        private void DeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            var model = this.grid.SelectedItem as PatientModel;
            if (model != null)
            {
                if (service.PatidExist(model.P_ID))
                {
                    if (!service2.DeletePatient(model))
                    {
                        if (Common.languageCode == "zh-CN")
                        {
                            LayUINotify.ShowInfo("删除失败");
                        }
                        else
                        {
                            LayUINotify.ShowInfo("Tip", "Delete Failed");
                        }
                        //LayUINotify.ShowInfo("删除失败");
                    }
                    else
                    {
                        if (Common.languageCode == "zh-CN")
                        {
                            LayUINotify.ShowInfo("删除成功");
                        }
                        else
                        {
                            LayUINotify.ShowInfo("Tip", "Delete Successful");
                        }
                        //LayUINotify.ShowInfo("删除成功");
                    }
                }
                else
                {
                    if (Common.languageCode == "zh-CN")
                    {
                        MessageBox.Show("未找到该病人");
                    }
                    else
                    {
                        MessageBox.Show("Patient Not Found");
                    }
                    //MessageBox.Show("未找到该病人");
                }
            }
        }


        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }













        public Task Load(int page, int pageSize)
        {
            return Task.Run(() =>
            {
                App.Current.Dispatcher.Invoke(() =>
                {
                    var list = patientList.Skip((page - 1) * pageSize).Take(pageSize).ToList();
                    //bindList = new ObservableCollection<PatientModel>(list);
                    patientList2 = list;
                    //grid.Items.Clear();
                    grid.ItemsSource = patientList2;
                });
            });
        }

        private void Paginator_Loaded(object sender, RoutedEventArgs e)
        {
            //initData();
            patientList = getPatient();
            openPatientsModel.RecordCount = patientList.Count;
            Load(1, openPatientsModel.PageSize);
        }

        private void Paginator_PageChanged(object arg1, Control.PageEventArgs arg2)
        {
            Paginator paginator = arg1 as Paginator;
            Load(paginator.Page, paginator.PageSize);
        }


        private async void UploadBtn_Click(object sender, RoutedEventArgs e)
        {
            var model = this.grid.SelectedItem as PatientModel;
            if (model == null)
            {
                if (Common.languageCode == "zh-CN")
                {
                    MessageBox.Show("请选择一个病人信息进行上传");
                }
                else
                {
                    MessageBox.Show("Please select a patient's information to upload");
                }
                //MessageBox.Show("请选择一个病人信息进行上传。");
                return;
            }

            var dicomClient = DicomConnectionManager.Instance.GetClient();
            if (dicomClient == null)
            {
                if (Common.languageCode == "zh-CN")
                {
                    MessageBox.Show("未连接到DICOM服务器");
                }
                else
                {
                    MessageBox.Show("Not Connected to DICOM Server");
                }
                //MessageBox.Show("未连接到DICOM服务器。");
                return;
            }

            bool success = await UploadPatientToDicomServer(model, dicomClient);
            if (success)
            {
                if (Common.languageCode == "zh-CN")
                {
                    MessageBox.Show("病人信息上传成功！");
                }
                else
                {
                    MessageBox.Show("Patient Information Upload Successful!");
                }
               // MessageBox.Show("病人信息上传成功！");
            }
            else
            {
                if (Common.languageCode == "zh-CN")
                {
                    MessageBox.Show("病人信息上传失败！");
                }
                else
                {
                    MessageBox.Show("Patient Information Upload Failed!");
                }
                //MessageBox.Show("病人信息上传失败。");
            }
        }

        private async Task<bool> UploadPatientToDicomServer(PatientModel model, IDicomClient dicomClient)
        {
            try
            {

                string dicomSex;
                switch (model.SEX)
                {
                    case "男":
                        dicomSex = "M";
                        break;
                    case "Male":
                        dicomSex = "M";
                        break;
                    case "女":
                        dicomSex = "F";
                        break;
                    case "Female":
                        dicomSex = "F";
                        break;
                    default:
                        dicomSex = string.Empty;
                        break;
                }


                var dataset = new DicomDataset(DicomTransferSyntax.ExplicitVRLittleEndian)
                   {
                       { DicomTag.SpecificCharacterSet, "ISO_IR 192" },
                       { DicomTag.PatientName, model.Name },
                       { DicomTag.PatientID, model.P_ID },
                       { DicomTag.PatientSex, dicomSex }, // 这里使用转换后的性别
                       { DicomTag.PatientBirthDate, model.Birth.ToString("yyyyMMdd") }, // DICOM 日期格式
                       { DicomTag.PatientAddress, model.Adreess },
                       { DicomTag.PatientTelephoneNumbers, model.PhoneNum },
                       { DicomTag.PatientComments, model.Email }, // 使用 PatientComments 存储 Email
                       { DicomTag.StudyInstanceUID, DicomUID.Generate() }, // Study Instance UID
                       { DicomTag.SeriesInstanceUID, DicomUID.Generate() }, // Series Instance UID
                       { DicomTag.SOPInstanceUID, DicomUID.Generate() }, // SOP Instance UID
                       { DicomTag.SOPClassUID, DicomUID.SecondaryCaptureImageStorage }, // SOP Class UID，使用 Secondary Capture Image Storage 作为示例
                       { DicomTag.Modality, "OT" }, // Modality (OT = Other)
                       { DicomTag.StudyID, "1" }, // Study ID
                       { DicomTag.SeriesNumber, "1" }, // Series Number
                       { DicomTag.InstanceNumber, "1" } // Instance Number
                    };

                // 使用适当的 DICOM 标签存储 "creator" 信息
                dataset.AddOrUpdate(DicomTag.ConsultingPhysicianName, model.Creator); // 使用 ConsultingPhysicianName 字段存储

                // 创建 DICOM 文件
                var dicomFile = new DicomFile(dataset);

                // 创建并添加 C-STORE 请求
                var request = new DicomCStoreRequest(dicomFile);
                await dicomClient.AddRequestAsync(request);

                // 发送请求
                await dicomClient.SendAsync();

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
                return false;
            }
        }




    }
}
